/**
 * ----------------------------------------------------------------------------
 * Copyright Jens Konopka
 * 
 * Alle Rechte vorbehalten.
 * Licence: Apache 2.0
 * ----------------------------------------------------------------------------
 *
 * created on 04.03.2012 by jkonopka
 */
package de.sql.toolkit.provider;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.sql.toolkit.manager.ConnectionManager;
import de.sql.toolkit.model.Column;
import de.sql.toolkit.util.SqlUtil;

/**
 * @author jkonopka
 * 
 */
public class SelectProvider implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1834136732577753453L;

	/**
	 * @param schema
	 * @param table
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> select(final String schema, final String table) throws Exception {
		final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		final Connection connection = ConnectionManager.getConnection();
		ResultSet result = null;
		Statement statement = null;

		try {

			final ColumnProvider columnProvider = new ColumnProvider();
			final List<Column> columns = columnProvider.select(schema, table);

			final StringBuilder sql = new StringBuilder();
			sql.append("SELECT * FROM ");
			sql.append(table);

			statement = connection.createStatement();
			result = statement.executeQuery(sql.toString());
			while (result.next()) {
				final Map<String, Object> map = new HashMap<String, Object>();
				for (final Column column : columns) {
					final String name = column.getName();
					map.put(name, result.getObject(name));
				}
				list.add(map);
			}

		} finally {
			SqlUtil.close(statement);
			SqlUtil.close(result);
		}
		return list;
	}

}
